package com.awesomeproject;

import com.facebook.react.bridge.ModuleSpec;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.modules.network.NetworkingModule;
import com.facebook.react.modules.network.NetworkingModuleUtils;
import com.facebook.react.shell.MainReactPackage;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Provider;

/**
 * <pre>
 *     author : ADMIN
 *     e-mail : wenju.tian@deltaww.com
 *     time   : 2019/10/08
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class CustomReactPackage extends MainReactPackage {

  @Override

  public List getNativeModules(ReactApplicationContext context) {

    List nativeModules = super.getNativeModules(context);

    return adjustModules(context, nativeModules);

  }

  private List adjustModules(ReactApplicationContext context, List moduleSpecs) {

    ArrayList modules = new ArrayList<ModuleSpec>(moduleSpecs);

    for (int i = 0; i < modules.size(); i++) {


      ModuleSpec spec = (ModuleSpec) modules.get(i);

      if (spec.getType().equals(NetworkingModule.class)) {

        modules.set(i, getCustomNetworkingModule(context));

        break;

      }

    }

    return modules;

  }

  private ModuleSpec getCustomNetworkingModule(final ReactApplicationContext context) {

    return ModuleSpec.nativeModuleSpec(

      NetworkingModule.class, new Provider<NativeModule>() {
        @Override
        public NativeModule get() {
          return NetworkingModuleUtils.createNetworkingModuleWithCustomClient(context);
        }
      }
    );

  }

}
